{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Grid snapping\n",
    "\n",
    "GDS represents points as integers where each point corresponds to a database unit (DBU). Typically, in most foundries, the default DBU is set to 1 nanometer (1nm).\n",
    "\n",
    "GDSFactory snaps ports to the grid by default to avoid grid snapping errors which are common in layout designs. \n",
    "\n",
    "If you want to connect components off-grid you need to create a virtual cell, which operates in floats instead of DBUs.\n",
    "\n",
    "\n",
    "![](https://i.imgur.com/SUXBWed.png)\n",
    "\n",
    "Example of grid snapping errors.\n",
    "\n",
    "![](https://i.imgur.com/suiHyqM.png)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": [
    "nm = 1e-3\n",
    "wg1 = gf.Component()\n",
    "wg1.add_polygon(\n",
    "    [(0, 0), (1.4 * nm, 0), (1.4 * nm, 1 * nm), (0, 1 * nm)], layer=(1, 0)\n",
    ")  # rounds to 1 nm\n",
    "\n",
    "wg1.add_polygon(\n",
    "    [(0, 3 * nm), (1.6 * nm, 3 * nm), (1.6 * nm, 4 * nm), (0, 4 * nm)], layer=(1, 0)\n",
    ")  # rounds to 2 nm\n",
    "\n",
    "wg1.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3",
   "metadata": {},
   "source": [
    "## Changing DBU\n",
    "\n",
    "The default DBU (database unit) is set to 1 nm, but you can customize it to other values, such as 5 nm, depending on your design requirements."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "gf.kcl.dbu = 5e-3 # set 1 DataBase Unit to 5 nm"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5",
   "metadata": {},
   "source": [
    "This script highlights the effect of rounding when the dbu is set to 5 nm. The discrepancies occur because the coordinate values are snapped to the nearest grid point, which is a multiple of 5 nm in this case.\n",
    "\n",
    "This can lead to visual or functional differences when designing components with precise tolerances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "wg1 = gf.Component()\n",
    "DBU = 5e-3\n",
    "LAYER = (1, 0)\n",
    "\n",
    "# Add polygons with intentional coordinates to show rounding errors.\n",
    "# Coordinate values that do not align perfectly with 5 nm dbu.\n",
    "polygon1_coords = [\n",
    "    (0, 0),\n",
    "    (1.7 * DBU, 0),  # 1.7 * 5 nm = 8.5 nm, which will round to 10 nm.\n",
    "    (1.7 * DBU, 1.3 * DBU),  # 1.3 * 5 nm = 6.5 nm, which will round to 5 nm.\n",
    "    (0, 1.3 * DBU)\n",
    "]\n",
    "wg1.add_polygon(polygon1_coords, layer=LAYER)\n",
    "\n",
    "polygon2_coords = [\n",
    "    (0, 2.1 * DBU),  # 2.1 * 5 nm = 10.5 nm, which will round to 10 nm.\n",
    "    (2.4 * DBU, 2.1 * DBU),  # 2.4 * 5 nm = 12 nm (aligned, no rounding).\n",
    "    (2.4 * DBU, 3.9 * DBU),  # 3.9 * 5 nm = 19.5 nm, which will round to 20 nm.\n",
    "    (0, 3.9 * DBU)\n",
    "]\n",
    "wg1.add_polygon(polygon2_coords, layer=LAYER)\n",
    "wg1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7",
   "metadata": {},
   "outputs": [],
   "source": [
    "gf.kcl.dbu = 1e-3 # Change back 1 DataBase Unit to 1 nm."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8",
   "metadata": {},
   "source": [
    "## ⚠️ Warning: Manhattan Orientations\n",
    "\n",
    "It's crucial to always maintain ports with Manhattan orientations (0, 90, 180, 270 degrees). Non-Manhattan ports can lead to ports snapping off the grid, resulting in 1nm gaps in your layouts, which can be detrimental to the design's integrity.\n",
    "\n",
    "Although **gdsfactory** provides functions to connect and route component ports that are off-grid or have non-Manhattan orientations.\n",
    "\n",
    "> **Note:** If you intend to create off-grid ports and non-Manhattan connections, you must enable this feature manually. This should be done with caution and a thorough understanding of the potential implications on your design."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "w1 = c << gf.c.straight(length=4 * nm, width=4 * nm)\n",
    "w1.rotate(45)\n",
    "\n",
    "w2 = c << gf.c.straight(length=4 * nm, width=4 * nm)\n",
    "w2.connect(\"o1\", w1[\"o2\"])\n",
    "c  # In this case ports overlap by an extra nm because of the rotation, instead of connecting them with no overlap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "w1 = c << gf.components.straight(length=4 * nm, width=4 * nm)\n",
    "w1.rotate(30)\n",
    "\n",
    "w2 = c << gf.components.straight(length=4 * nm, width=4 * nm)\n",
    "w2.connect(\"o1\", w1[\"o2\"])\n",
    "c  # In this case ports have a 1nm gap error because of the rotation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11",
   "metadata": {},
   "source": [
    "\n",
    "## Fix Non manhattan connections\n",
    "\n",
    "The GDS format often has issues with non-manhattan shapes, due to the rounding of vertices to a unit grid and to downstream tools (i.e. DRC) which often tend to assume cell references only have rotations at 90 degree intervals.\n",
    "\n",
    "To fix it, you can insert them as virtual instances.\n",
    "\n",
    "For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "nm = 1e-3\n",
    "c = gf.Component()\n",
    "w = gf.components.straight(length=4 * nm, width=4 * nm)\n",
    "\n",
    "# An instance of component w1 is added to the main component c and then rotated by 30 degrees.\n",
    "w1 = c.add_ref_off_grid(w)\n",
    "w1.rotate(30)\n",
    "\n",
    "# A second instance of w is added.\n",
    "# The connect function then automatically moves and rotates this second instance (w2),\n",
    "# so that its input port (o1) is perfectly aligned with the output port (o2) of the first, rotated instance (w1).\n",
    "w2 = c.add_ref_off_grid(w)\n",
    "w2.connect(\"o1\", w1[\"o2\"])\n",
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "13",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "\n",
    "def demo_non_manhattan():\n",
    "    c = gf.Component()\n",
    "    b = c << gf.components.bend_circular(angle=30)\n",
    "    s = c << gf.components.straight(length=5)\n",
    "    s.connect(\"o1\", b.ports[\"o2\"])\n",
    "    return c\n",
    "\n",
    "\n",
    "c1 = demo_non_manhattan()\n",
    "c1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "14",
   "metadata": {},
   "source": [
    "if you zoom in between the bends you will see a notch between waveguides due to non-manhattan connection between the bends.\n",
    "\n",
    "![gap](https://i.imgur.com/jBEwy9T.png)\n",
    "\n",
    "\n",
    "## Solution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "\n",
    "@gf.vcell\n",
    "def snap_bends() -> gf.ComponentAllAngle:\n",
    "\n",
    "    # Instead of a standard gf.Component, a ComponentAllAngle is created.\n",
    "    # This special container is necessary for managing shapes that are not restricted to 90-degree angles.\n",
    "    c = gf.ComponentAllAngle()\n",
    "\n",
    "    # A 37-degree Euler bend, designed for low-loss arbitrary angle turns, is created.\n",
    "    # Two instances are placed in the component, and the second (b2) is connected to the end of the first (b1) to create a continuous, smooth curve.\n",
    "    b = gf.c.bend_euler_all_angle(angle=37)\n",
    "    b1 = c << b\n",
    "    b2 = c << b\n",
    "    b2.connect(\"o1\", b1.ports[\"o2\"])\n",
    "    c.add_port(\"o1\", port=b1.ports[\"o1\"])\n",
    "    c.add_port(\"o2\", port=b2.ports[\"o2\"])\n",
    "    return c\n",
    "\n",
    "# The final component c consists of the two 37-degree bends connected end-to-end, forming a single waveguide path that turns by a total of 74 degrees.\n",
    "c = snap_bends()\n",
    "c.show()\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "16",
   "metadata": {},
   "source": [
    "If you zoom into the connection you will now see a perfect connection:\n",
    "\n",
    "![no gap](https://i.imgur.com/VbSgIjP.png)"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "custom_cell_magics": "kql"
  },
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
